<!-- API文档组件 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="API文档"
    width="800px"
  >
    <el-tabs v-model="activeTab">
      <el-tab-pane label="Python" name="python">
        <div class="code-block">
          <div class="code-header">
            <span>Python 示例代码</span>
            <el-button type="primary" link @click="copyCode('python')">复制代码</el-button>
          </div>
          <pre><code>import requests

def validate_uuid(uuid):
    """
    验证UUID
    :param uuid: 要验证的UUID字符串
    :return: (bool, str) - (是否成功, 错误信息)
    """
    try:
        response = requests.get(
            "https://web.tjbbb.com/api/uuid/validate",
            params={"uuid": uuid}
        )
        result = response.json()
        
        if response.status_code == 200 and result.get("code") == 0:
            return True, "验证成功"
        else:
            return False, result.get("msg", "验证失败")
    except Exception as e:
        return False, str(e)

# 使用示例
uuid = "your-uuid-here"
success, message = validate_uuid(uuid)
print(f"验证结果: {message}")</code></pre>
        </div>
      </el-tab-pane>

      <el-tab-pane label="JavaScript" name="javascript">
        <div class="code-block">
          <div class="code-header">
            <span>JavaScript 示例代码</span>
            <el-button type="primary" link @click="copyCode('javascript')">复制代码</el-button>
          </div>
          <pre><code>// 使用 fetch API
async function validateUUID(uuid) {
  try {
    const response = await fetch(
      `https://web.tjbbb.com/api/uuid/validate?uuid=${encodeURIComponent(uuid)}`
    );
    const result = await response.json();
    
    if (response.ok && result.code === 0) {
      const expiryMessage = result.data?.expiryMessage || '未知';
      return { 
        success: true, 
        message: "验证成功", 
        expiryMessage: expiryMessage 
      };
    } else {
      return { success: false, message: result.msg || "验证失败" };
    }
  } catch (error) {
    return { success: false, message: error.message };
  }
}

// 使用示例
const uuid = "your-uuid-here";
validateUUID(uuid)
  .then(({ success, message, expiryMessage }) => {
    console.log(`验证结果: ${message}`);
    if (success) {
      console.log(`${expiryMessage}`);
    }
  });</code></pre>
        </div>
      </el-tab-pane>

      <el-tab-pane label="SAS" name="sas">
        <div class="code-block">
          <div class="code-header">
            <span>SAS 示例代码</span>
            <el-button type="primary" link @click="copyCode('sas')">复制代码</el-button>
          </div>
          <pre><code>%macro validate_uuid(uuid=);
  filename resp temp;
  
  proc http
    url="https://web.tjbbb.com/api/uuid/validate?uuid=%sysfunc(urlencode(&uuid))"
    method="GET"
    out=resp;
  run;
  
  libname respjson json fileref=resp;
  
  data _null_;
    set respjson.root;
    if code = 0 then do;
      put "验证成功";
    end;
    else do;
      put "验证失败: " msg;
    end;
  run;
  
  filename resp clear;
  libname respjson clear;
%mend;

/* 使用示例 */
%validate_uuid(uuid=your-uuid-here);</code></pre>
        </div>
      </el-tab-pane>

      <el-tab-pane label="接口说明" name="docs">
        <h3>接口详情</h3>
        <el-descriptions border>
          <el-descriptions-item label="接口地址">https://web.tjbbb.com/api/uuid/validate</el-descriptions-item>
          <el-descriptions-item label="请求方式">GET</el-descriptions-item>
          <el-descriptions-item label="参数">uuid: string (必填) - 要验证的UUID</el-descriptions-item>
        </el-descriptions>

        <h3 class="mt-4">响应格式</h3>
        <pre><code>{
  "code": 0,       // 0表示成功，非0表示失败
  "msg": "string", // 响应信息
  "data": null     // 无返回数据
}</code></pre>

        <h3 class="mt-4">错误码说明</h3>
        <el-table :data="errorCodes" border>
          <el-table-column prop="code" label="错误码" width="100" />
          <el-table-column prop="message" label="说明" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ApiDoc',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  emits: ['update:visible'],
  setup(props, { emit }) {
    const activeTab = ref('python')
    const baseUrl = 'https://web.tjbbb.com/api'
    
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })

    const errorCodes = [
      { code: 0, message: '验证成功' },
      { code: 7, message: 'UUID不存在' },
      { code: 8, message: 'UUID未激活' },
      { code: 9, message: 'UUID已过期' },
      { code: 10, message: 'UUID当日访问次数已达上限' },
      { code: 11, message: 'UUID总访问次数已达上限' }
    ]

    const getCode = (type) => {
      const codeBlocks = {
        python: document.querySelector('[name="python"] code'),
        javascript: document.querySelector('[name="javascript"] code'),
        sas: document.querySelector('[name="sas"] code')
      }
      return codeBlocks[type]?.textContent || ''
    }

    const copyCode = async (type) => {
      try {
        const code = getCode(type)
        await navigator.clipboard.writeText(code)
        ElMessage.success('代码已复制到剪贴板')
      } catch (err) {
        console.error(err)
        ElMessage.error('复制失败')
      }
    }

    return {
      activeTab,
      baseUrl,
      errorCodes,
      dialogVisible,
      copyCode
    }
  }
}
</script>

<style lang="scss" scoped>
.code-block {
  background-color: #f5f7fa;
  border-radius: 4px;
  
  .code-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    border-bottom: 1px solid #dcdfe6;
  }
  
  pre {
    margin: 0;
    padding: 16px;
    
    code {
      font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
      font-size: 14px;
      line-height: 1.5;
      white-space: pre-wrap;
    }
  }
}

.mt-4 {
  margin-top: 16px;
}
</style> 